<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" center type="info" show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeName-0" :align-center='true'>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form :label-position="'top'" :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-tabs :before-leave='beforeLeave' :tab-position="'left'" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="activeCate" :options="cateListData" :props="props" @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in goodsCate" :key="item.attr_id">
              <!-- checkbox多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" :prop="item.attr_vals" v-for="item in cateOnlyList"
              :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :on-success="imgSuccess" :headers='headers'
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor  v-model="addForm.goods_introduce"></quill-editor>
             <el-button type="primary" @click="addFormbtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片缩略图 -->
    <el-dialog title="缩略图" :visible.sync="imgPreview" width="50%" >
      <img :src="imgDialogURL" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 切换键值
      activeName: '0',
      // 添加表单数据源
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        attrs: [],
        pics: [],
        goods_introduce: ''
      }, // 添加表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类数据源
      cateListData: [],
      activeCate: [],
      props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 商品参数
      goodsCate: [],
      // 商品属性
      cateOnlyList: [],
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片缩略图
      imgPreview: false,
      // 缩略图ulr
      imgDialogURL: ''
    }
  },
  created () {
    this.getCate()
  },
  methods: {
    // 点击tabs触发事件
    handleClick () {
      // if (this.activeName === '1') {
      //   // 获取商品参数列表
      //   this.getManyList()
      // } else if (this.activeName === '2') {
      //   console.log(1)
      // }
    }, // 获取分类数据
    async getCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('商品分类获取失败')
      }
      this.cateListData = res.data
    },
    // 改变级联选择器触发事件
    handleChange () {
      if (this.activeCate.length !== 3) {
        this.activeCate = []
      }
    },
    // 钩子函数，点击tabs切换，钩子
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.activeCate.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      } else if (activeName === '1') {
        // 商品参数
        this.getManyList()
      } else if (activeName === '2') {
        // 商品属性
        this.getOnlyList()
      } else if (activeName === '3') {
        console.log(3)
      }
    },
    // 获取动态参数
    async getManyList () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: 'many'
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('商品参数获取失败')
      }
      res.data.forEach((item) => {
        item.attr_vals =
          item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
      })
      this.goodsCate = res.data
    }, // 获取静态属性，
    async getOnlyList () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: 'only'
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('商品属性获取失败')
      }
      this.cateOnlyList = res.data
      console.log(this.cateOnlyList)
    }, // 图片预览
    handlePreview (file) {
      console.log(file)
      this.imgDialogURL = file.response.data.url
      this.imgPreview = true
    },
    // 移除时触发的钩子
    handleRemove (file) {
      const i = this.addForm.pics.findIndex((item) => {
        return item.pics === file.response.data.tmp_path
      })
      this.addForm.pics.splice(i, 1)
    },
    imgSuccess (file) {
      if (file.meta.status !== 200) return
      const pics = {
        pics: file.data.tmp_path
      }
      this.addForm.pics.push(pics)
    },
    // 提交表单按钮
    addFormbtn () {
      this.addForm.goods_cat = this.activeCate.join(',')
      this.goodsCate.forEach(item => {
        const manyInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        }
        this.addForm.attrs.push(manyInfo)
      })
      this.cateOnlyList.forEach(item => {
        const onlyInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addForm.attrs.push(onlyInfo)
      })
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入表单必填项')
        const { data: res } = await this.$http.post('goods', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      if (this.activeCate.length === 3) {
        return this.activeCate[2]
      }
      return null
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-checkbox {
  margin: 0 20px 0px 0px !important;
}
.previewImg{
  width: 100%;
}
</style>
